package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class MemberController {
    @Reference
    MemberService memberService;

    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map map) {
        //1.验证码比对
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {

            Member member = memberService.findMemberBytelephone(telephone);
            //2.判断用户是否是会员，第一次还是第N次登陆
            if (member == null) {
                //规避空指针
                member = new Member();
                //第一次登陆，自动注册为会员
                member.setRegTime(new Date());

                memberService.add(member);
            }
            //3.发送Cookie至客户端，存储用户电话号
            Cookie cookie = new Cookie("login_member_phone", telephone);
            cookie.setPath("/");
            //设置过期时间30天
            cookie.setMaxAge(30*24*60*60);
            response.addCookie(cookie);
            //4.用Redis代替Session存储用户信息
            String json = JSON.toJSON(member).toString();
            //以电话为键，member的json串为值，设置过期时间30分钟
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }
}
